﻿/**************************************************************************
创建时间:	2020/5/14
作	  者:	张存
邮 	  箱:	zhangcunliang@126.com

Copyright (c) zhcun.cn

描	述：
记	录：
***************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ZhCun.Utils.Helpers;
using ZhCun.Win.Extend;

namespace ZhCun.Win
{
    public static class ControlRights
    {      
        /// <summary>
        /// 初始化控件权限
        /// </summary>
        public static void InitControlRights(this FrmBase frm)
        {
            // 格式: A-控件1.控件1子级...[设置控件]:true|false;
            // 格式: "A-控件1.子级控件.子级控件...[要设置的控件]:true|false;"

            string arg = frm.ControlRightsArgs;
            
            if (arg.IsEmpty()) return;

            //这里不需要做异常判断,异常是因为配置出错,应该找出配置错的原因并修改;
            var rgArgs = arg.SplitByNotEmpty(";");
            Control tmpCtr;
            bool isVisible;
            string controlType;
            string tmpArg;
            foreach (var itemArg in rgArgs)
            {
                //A: 工具栏,
                controlType = itemArg.Substring(0, 1);
                //移除前两位类型标识
                tmpArg = itemArg.Remove(0, 2);
                var ctrSet = tmpArg.SplitByNotEmpty(":");
                var ctrTree = ctrSet[0].SplitByNotEmpty("."); //SplitStr(ctrSet[0], '.');
                //var setVal = ctrSet[1];
                isVisible = ctrSet[1].StringEquals("true");
                tmpCtr = frm;
                foreach (var item in ctrTree)
                {
                    tmpCtr = tmpCtr.Controls[item];
                    if (controlType == "A")
                    {   // 工具栏
                        if (tmpCtr is ToolStrip toBar)
                        {
                            var toolItemName = ctrTree[ctrTree.Length - 1];
                            toBar.Items[toolItemName].Enabled = isVisible;
                            toBar.Items[toolItemName].Visible = isVisible;
                            break;
                        }
                    }
                }

                if (controlType == "B")
                {
                    //控件直接赋值
                    tmpCtr.Enabled = isVisible;
                    tmpCtr.Visible = isVisible;
                }
            }
        }
    }
}
